package cn.matezk.lianlian.task;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.dao.DeviceDao;
import cn.matezk.lianlian.model.Device;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.iotexplorer.v20190423.IotexplorerClient;
import com.tencentcloudapi.iotexplorer.v20190423.models.DescribeDeviceDataRequest;
import com.tencentcloudapi.iotexplorer.v20190423.models.DescribeDeviceDataResponse;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class IccidSyncTask {
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private IotexplorerClient tencentClient;

    @XxlJob("iccidSyncTask")
    public void execute() {
        List<String> deviceIds = deviceDao.selectEmptyIccid();
        for (String deviceId : deviceIds) {
            String deviceName = deviceId.split("/")[1];
            if (!deviceName.startsWith("86"))   continue;
            String productId = deviceId.split("/")[0];
            DescribeDeviceDataRequest request = new DescribeDeviceDataRequest();
            request.setProductId(productId);
            request.setDeviceName(deviceName);
            DescribeDeviceDataResponse response;
            try {
                response = tencentClient.DescribeDeviceData(request);
            } catch (TencentCloudSDKException e) {
                XxlJobHelper.log(e);
                continue;
            }
            String data = response.getData();
            JSONObject obj = JSONUtil.parseObj(data);
            if (!obj.containsKey("iccid"))   continue;
            String iccid = obj.getJSONObject("iccid").getStr("Value", "");
            if (ObjectUtil.isEmpty(iccid))  continue;
            Device device = new Device();
            device.setDeviceId(deviceId);
            device.setIccid(iccid);
            deviceDao.updateByPrimaryKeySelective(device);
        }
    }
}
